/*
 * The MIT License
 *
 * Copyright (c) 2013-2016 reark project contributors
 *
 * https://github.com/reark/reark/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.reark.rxgithubapp.advanced.widget;

import io.reark.rxgithubapp.advanced.data.DbUtils;
import io.reark.rxgithubapp.advanced.data.GithubDb;
import io.reark.rxgithubapp.advanced.data.UserSettings;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentProvider;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.event.notification.NotificationRequest;
import ohos.rpc.IRemoteObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class WidgetService extends Ability {
    private static final String TAG = WidgetService.class.getSimpleName();
    private static final int NOTICE_ID = 1005;
    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect = null;
    Timer timer;

    @Override
    public void onStart(Intent intent) {
        startTimer();
        super.onStart(intent);
        System.out.println("----------->服务 onStart" + TAG);
    }

    /**
     * 卡片更新定时器, 每秒更新一次
     */
    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
        }

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateForms();
                notice();
            }
        }, 0, 1000L);
    }
    public void updateForms() {

        if (connect == null) {
            connect = helper.getOrmContext(DbUtils.A_LIAS, DbUtils.DB, GithubDb.class);
        }
        OrmPredicates ormPredicates = new OrmPredicates(UserSettings.class);
        List<UserSettings> userSettingsList = connect.query(ormPredicates);
        if (userSettingsList.size() < 1) {
            return;
        }
        for (UserSettings userSettings : userSettingsList) {
            // 遍历卡片列表更新卡片
            ComponentProvider componentProvider = WidgetProvider.getComponentProvider(this);
            Long updateFormId = userSettings.getId();
            try {
                updateForm(updateFormId, componentProvider);
            } catch (FormException e) {
                DbUtils.delete(updateFormId, connect);

            }
        }
    }

    private String getCurrentDate() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }

    private void notice() {
        // 创建通知
        NotificationRequest request = new NotificationRequest(NOTICE_ID);
        request.setAlertOneTime(true);
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        content.setText(getCurrentDate());
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);
        // 绑定通知
        keepBackgroundRunning(NOTICE_ID, request);
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
        System.out.println("----------->服务 onCommand" + TAG);
        if (connect == null) {
            connect = helper.getOrmContext(DbUtils.A_LIAS, DbUtils.DB, GithubDb.class);
        }
        super.onCommand(intent, restart, startId);
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        System.out.println("----------->服务 onConnect" + TAG);
        return super.onConnect(intent);
    }

    @Override
    public void onDisconnect(Intent intent) {
        super.onDisconnect(intent);
        System.out.println("----------->服务 onDisconnect" + TAG);
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("----------->服务 onStop");
        timer.cancel();
        System.out.println("----------->timer 停止了");

    }
}
